package org.wattdepot.cli.commands;

import java.util.ArrayList;
import java.util.List;
import org.wattdepot.client.WattDepotClient;
import org.wattdepot.client.WattDepotClientException;
import org.wattdepot.resource.source.jaxb.Source;

/**
 * This class contains a command that prints out a list of sources for the CommandLineInterface.
 * 
 * @author David Mau
 */
public class ListSourcesCommand implements WattDepotCliCommand {
  // Default client-server connection to use unless given one.
  private WattDepotClient client = new WattDepotClient(debug);

  /**
   * This constructor makes sure that the client really is connected to the server.
   * 
   * @param anotherClient Specifies if the user wants to use another WattDepot server
   * other than the default simulation one.
   */
  public ListSourcesCommand( String anotherClient ) {
    // If another client is provided
    if ( anotherClient != null ) {
      client = new WattDepotClient( anotherClient );
    }

    // Stop right away if we cannot contact server.
    if (!client.isHealthy()) {
      System.out.println("Failed to connect to " + client.getWattDepotUri());
      return;
    }
    // Indicate successful connection.
    //System.out.println("Connected to " + client.getWattDepotUri());
  }

  /**
   * This method returns a String that contains all of the public sources in the system. The String
   * is ready to print in a table format.
   * 
   * Created by David Mau.
   * 
   * @param args A list of arguments for this command.
   * @return A String containing a table of sources.
   */
  public String doCommand(List<String> args) {
    String output;

    if (!args.isEmpty()) {
      output = tooManyArguments;
      output = output.concat(cr);
      return output;
    }

    int count;
    int counter = 0;

    List<Source> sources;

    try {
      // Get all sources from the client
      sources = client.getSources();

      // Check how many sources there are.
      count = sources.size();

      String[] names = new String[count];
      String[] parents = new String[count];
      String[] descriptions = new String[count];

      // Go through the list of sources
      for (Source single : sources) {
        // Get basic information
        names[counter] = single.getName();
        parents[counter] = "";
        descriptions[counter] = single.getDescription();

        counter++;
      }

      counter = 0;

      // Now that all of the sources are in the arrays,
      // Place the parents in the right places.
      for (Source single : sources) {
        // If one of the sources is a parent to another source...
        if (single.isSetSubSources()) {
          // Get a list of the children of the source
          List<String> childList = single.getSubSources().getHref();
          // For each child listed, add the parent's name to the
          // correct spot in the array.
          for (String test : childList) {
            // Break the given url up.
            // The fifth item in the array is a String of the child
            String[] urlBreak = test.split("/");
            ArrayList<String> brokenUrl = new ArrayList<String>();
            for ( String url : urlBreak ) {
              brokenUrl.add( url );
            }
            int lastIndex = brokenUrl.size() - 1;
            // Go through all of the names in the array
            while (counter < count) {
              // If the entry name matches the child's name
              if (names[counter].compareTo(brokenUrl.get( lastIndex )) == 0) {
                // Put the name of the parent in the right place
                parents[counter] = single.getName();
              }

              counter++;
            }
            // Reset counter.
            counter = 0;
          }
        }
      }
      // Start creating the table
      output = "Name             Parent           Description";
      output = output.concat(cr);

      // Place the output in the table
      while (counter < count) {
        output =
            output.concat(String.format("%-16s %-16s %s", names[counter], parents[counter],
                descriptions[counter]));
        output = output.concat(cr);

        counter++;
      }
    }
    catch (WattDepotClientException e) {
      output = serverConnectionError;
      output = output.concat(e.toString());
      output = output.concat(cr);
    }

    // Output the table
    return output;

  }

}
